﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;


public partial class Manager_Revenue_OrderDetail : System.Web.UI.Page
{
    protected int iPageIndex = 0;
    public string MenuID = "";
    public decimal p_Quantity, p_Total;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
        }
        clsWebShop cls = new clsWebShop();
        DataTable dtMn = cls.GetData("select MenuID From Menu where MenuURL like '%~/Manager/OrderDetail/OrderDetail.aspx%'").Tables[0];

        if (dtMn.Rows.Count > 0)
        {
            MenuID = dtMn.Rows[0]["MenuID"].ToString();
        }
        else
        {
            return;
        }
        if (!IsPostBack)
        {




            txtDDH.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + btnSearch.ClientID + "').click();return false;}} else {return true}; ");

            if (Request.QueryString["PageIndex"] != "" && Request.QueryString["PageIndex"] != null)
            {
                iPageIndex = int.Parse(Request.QueryString["PageIndex"]);
                grvMaster.PageIndex = iPageIndex;
            }
            Bind_Order();


        }
    }




    private void Bind_Order()
    {
        clsWebShop cls = new clsWebShop();
        //Lay so luong trong kho
        Session["dtCountStore"] = cls.Get_QuantityStoreGroup("", "0").Tables[0];
        PccMsg msg = new PccMsg();
        DataTable dt = new DataTable();
        string sDate = "", eDate = "";
        sDate = Request.QueryString["sDate"];
        eDate = Request.QueryString["eDate"];
        if (Request.QueryString["type"] == "out")
        {
            msg.CreateFirstNode("StartDate", sDate);
            msg.CreateFirstNode("EndDate", eDate);
            msg.CreateFirstNode("Status", "E");
            msg.CreateFirstNode("End_MK", "");
            msg.CreateFirstNode("OrderID", txtDDH.Text);
            msg.CreateFirstNode("UserID", "0");
            msg.CreateFirstNode("CusNm", txtCusNm.Text);
            dt = cls.Get_OrderPDOverViewByCondition(msg.GetXmlStr.ToString()).Tables[0];
        }
        else
        {
            msg.CreateFirstNode("StartDate", sDate);
            msg.CreateFirstNode("EndDate", eDate);
            msg.CreateFirstNode("OrderID", txtDDH.Text);
            msg.CreateFirstNode("CusNm", txtCusNm.Text);
            dt = cls.Get_OrderRevenueByCondition(msg.GetXmlStr.ToString()).Tables[0];
        }










        BindData(dt);

    }

    private void BindData(DataTable dt)
    {
        grvMaster.DataSource = dt;
        grvMaster.DataBind();

    }
    protected void grvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label hplOrderID = new Label();
        clsCommon clsCom = new clsCommon();
        switch (e.Row.RowType)
        {

            case DataControlRowType.Header:
                if (Request.QueryString["type"] == "in")
                {
                    e.Row.Cells[4].Text = "Giá gốc";
                    e.Row.Cells[3].Text = "Số lượng kho";
                }
                break;
            case DataControlRowType.DataRow:
                e.Row.Attributes.Add("onmouseover", "this.className='cursorOverGrid'");
                if (e.Row.RowIndex % 2 == 0)
                    e.Row.Attributes.Add("onmouseout", "this.className='gvRowStyle'");
                else
                    e.Row.Attributes.Add("onmouseout", "this.className='gvAlternatingRowStyle'");

                string End_MK = DataBinder.Eval(e.Row.DataItem, "End_MK").ToString();
                string U_Status = DataBinder.Eval(e.Row.DataItem, "U_Status").ToString();
                if (End_MK == "D") //Don & KH dang o trang thai xoa
                {
                    e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
                }
                if (U_Status == "D")
                {
                    e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
                }

                e.Row.Cells[0].Text = "<a style='color:Navy;cursor:pointer' href='#' onclick='fnPrintOrder(\"" + MenuID + "\",\"" + DataBinder.Eval(e.Row.DataItem, "OrderID").ToString() + "\",\"E\")') ><img src='../../Images/Icon/cmdPrint.gif' border='0'></a>";

                hplOrderID = (Label)(e.Row.Cells[0].FindControl("hplOrderID"));
                hplOrderID.Text = "<font color='Green'>" + DataBinder.Eval(e.Row.DataItem, "OrderID").ToString().ToUpper() + "</font>";

                string Total = DataBinder.Eval(e.Row.DataItem, "ToTal").ToString();
                string Quantity = DataBinder.Eval(e.Row.DataItem, "Quantity").ToString();
                /*if (Request.QueryString["type"] == "out")
                {
                    Total = DataBinder.Eval(e.Row.DataItem, "ToTalOut").ToString();
                    Quantity = DataBinder.Eval(e.Row.DataItem, "Quantity").ToString();
                }
                */

                p_Quantity += clsCom.ConvertToDecimal(Quantity);
                p_Total += clsCom.ConvertToDecimal(Total);
                e.Row.Cells[3].Text = Quantity;
                e.Row.Cells[4].Text = FormatMoney(Total);

                break;
            case DataControlRowType.EmptyDataRow:

                e.Row.Cells[0].Text = "<span style='background-color:yellow;font-size:12px;font-weight:bold'>Không tìm thấy loại đơn đặt hàng nào trong ngày này</span>";
                e.Row.HorizontalAlign = HorizontalAlign.Center;
                e.Row.BorderWidth = Unit.Empty;
                e.Row.Cells[0].Height = Unit.Pixel(200);
                break;

            case DataControlRowType.Footer:

                e.Row.Cells[0].Text = "<b>Tổng cộng</b>";
                e.Row.Cells[0].ColumnSpan = 3;
                e.Row.Cells[3].Text = p_Quantity.ToString();
                e.Row.Cells[4].Text = clsCom.FormatMoney(p_Total.ToString());


                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
                e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Center;
                e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right;

                //e.Row.Cells(0).CssClass = "cssBorderGrv";
                //e.Row.Cells(5).CssClass = "cssBorderGrv";
                //e.Row.Cells(6).CssClass = "cssBorderGrv";
                //e.Row.Cells(4).CssClass = "cssBorderGrv";

                e.Row.Cells.RemoveAt(1);
                e.Row.Cells.RemoveAt(1);

                break;

        }
    }

    private string FormatMoney(string sNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", decimal.Parse(sNum));
        }
        catch (Exception) { }
        return sReturn;
    }


    private string FormatMoney(decimal dNum)
    {
        string sReturn = "0";
        try
        {
            sReturn = string.Format("{0:###,###,##0}", dNum);
        }
        catch (Exception) { }
        return sReturn;
    }
    private string FormatDate(string sDate)
    {
        string sReturn = "";
        try
        {
            sReturn = sDate.ToString().Substring(6, 2) + "/" + sDate.ToString().Substring(4, 2) + "/" + sDate.ToString().Substring(0, 4);
        }
        catch (Exception ex) { }

        return sReturn;
    }
    private string FormatDateTime(string sDate)
    {
        string sReturn = "";
        try
        {
            sReturn = sDate.ToString().Substring(6, 2) + "/" + sDate.ToString().Substring(4, 2) + "/" + sDate.ToString().Substring(0, 4);
            sReturn += "  " + sDate.ToString().Substring(8, 2) + ":" + sDate.ToString().Substring(10, 2) + ":" + sDate.ToString().Substring(12, 2);
        }
        catch (Exception ex) { }

        return sReturn;
    }
    #region "Export_ToExcel"
    private void ExportToExcel()
    {
        clsCommon clsCom = new clsCommon();
        grvMaster.EnableViewState = false;
        // Set the content type to Excel.
        Response.Clear();
        Response.Buffer = true;

        Response.ContentEncoding = System.Text.UnicodeEncoding.UTF8;
        Response.AppendHeader("Content-disposition", "attachmentfilename=DetailOrderDay.xls");
        Response.ContentType = "application/vnd.ms-excel";
        // / "application/x-msexcel"

        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        hw.WriteFullBeginTag("HTML");
        hw.WriteFullBeginTag("HEAD");

        string sStyle = "";

        sStyle += " .MergeCellRow{background:#e2ffcc;color:Black;font-weight:bold;font-size:10pt;font-family:Verdana;vertical-align:middle;text-align:center;border-top-color: #407db3;border-left-color: #407db3;border-right-color: #407db3;border-bottom-color: #407db3;}";
        sStyle += ".cssBorderGrv{border-top-color: #407db3;border-left-color: #407db3;border-right-color: #407db3;border-bottom-color: #407db3;}";
        sStyle += ".gvRowStyle{color:Black;	background:#feffeb;vertical-align:middle;border-top-color: black;border-left-color: black;border-right-color: black;border-bottom-color: black;}";
        sStyle += ".cssHeader{height:30px;BACKGROUND-COLOR: #D8ECFF;text-align:center;color:#000000;font-weight:bold;}";
        sStyle += ".gvAlternatingRowStyle{color:Black;background:#ffffff;vertical-align:middle;border-top-color: black;border-left-color: black;border-right-color: black;border-bottom-color: black;}";
        sStyle += ".gvAlternatingRowFooter{background:#f5e38a;color:Black;font-size:10pt;font-family:Verdana;vertical-align:middle;border-top-color: Black;border-left-color: Black;border-right-color: Black;border(-bottom - Color) : Black()}";
        sStyle += ".gvFooter{background:Silver;color:Black;font-weight:bold;font-size:10pt;font-family:Verdana;	vertical-align:middle;border-top-color: black;border-left-color: black;border-right-color: black;border-bottom-color: black;}";
        sStyle += ".kindmk2_total_value { COLOR: #000000 BACKGROUND-COLOR: #ccffffBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solid TEXT-ALIGN: rightVERTICAL-ALIGN:middle }";
        sStyle += ".sharehour { COLOR: #ff3300 BACKGROUND-COLOR: #ffff00 TEXT-ALIGN: rightBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solid}";
        sStyle += ".sharehourfee {COLOR: #ff3300 BACKGROUND-COLOR: #ffff00 TEXT-ALIGN: rightBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidFONT-WEIGHT: bold}";
        sStyle += ".sharehourfee1 {COLOR: #ff3300 BACKGROUND-COLOR: #ffff00 TEXT-ALIGN: centerBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidFONT-WEIGHT: bold}";
        sStyle += ".sharefee { COLOR: #ff3300 BACKGROUND-COLOR: #ffff00 TEXT-ALIGN: right }";
        sStyle += ".sharefee1 { COLOR: #ff3300 BACKGROUND-COLOR: #ffff00TEXT-ALIGN: centerBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidFONT-WEIGHT: bold}";
        sStyle += ".sharefee2 { COLOR: #ff3300 BACKGROUND-COLOR: #ffff00TEXT-ALIGN: leftBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidFONT-WEIGHT: bold}";
        sStyle += ".fd_sharefee {COLOR: #ff3300 BACKGROUND-COLOR: #ffff00 TEXT-ALIGN: centerBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidFONT-WEIGHT: bold}";
        sStyle += ".value_left{COLOR: #000000 BACKGROUND-COLOR: #ffffffTEXT-ALIGN:leftBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solid}.value_right{COLOR: #000000 BACKGROUND-COLOR: #ffffffTEXT-ALIGN:rightBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solid}.rb_center{TEXT-ALIGN:centerBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solid}.fdb_header_stt{COLOR: #000000 BACKGROUND-COLOR: #99ccff TEXT-ALIGN: centerBORDER-RIGHT: #000000 1px solid BORDER-BOTTOM: #000000 1px solidBORDER-TOP:#000000 1px solidBORDER-TOP:#000000 1px solid}";

        hw.RenderBeginTag(HtmlTextWriterTag.Style);
        hw.Write("<!--");
        hw.WriteLine(sStyle);
        hw.Write("-->");
        hw.RenderEndTag();

        hw.WriteEndTag("HEAD");
        hw.WriteFullBeginTag("BODY");

        // Get the HTML for the control	
        hw.WriteFullBeginTag("DIV align=center");
        hw.Write("<span style=color:Red; size:8pt>CHI TIẾT ĐƠN ĐẶT HÀNG NGÀY " + clsCom.FormatDate(DateTime.Now.ToString("dd/MM/yyyy")) + "</span>");
        hw.WriteEndTag("DIV");

        HtmlForm frm = new HtmlForm();
        this.Controls.Clear();
        this.Controls.Add(frm);

        frm.Controls.Add(grvMaster);

        frm.RenderControl(hw);

        hw.WriteEndTag("BODY");
        hw.WriteEndTag("HTML");

        // Write the HTML back to the browser.
        Response.Write(tw.ToString());
        Response.Flush();
        // End the response.
        Response.End();
    }
    #endregion
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Bind_Order();
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        Bind_Order();
    }
    protected void imgExportExcel_Click(object sender, ImageClickEventArgs e)
    {
        Bind_Order();
        ExportToExcel();
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        bool flagNone = true;
        string sOrderID = "";
        for (int i = 0; i < grvMaster.Rows.Count; i++)
        {
            CheckBox chkApprove = (CheckBox)grvMaster.Rows[i].FindControl("chkApprove");

            if (chkApprove.Checked == true)
            {
                /*string sOrderID = grvMaster.DataKeys[i].Value.ToString();
                cls.UpdateData("update OrderPD set Status='Y',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");
                flagNone = false;*/

                sOrderID = grvMaster.DataKeys[i].Value.ToString();
                PccMsg msg = new PccMsg();
                msg.CreateFirstNode("OrderID", sOrderID);
                msg.CreateFirstNode("flag", "2");
                msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                string xml = cls.Upd_SignPD(msg.GetXmlStr);
                msg = new PccMsg(xml);
                string strOutput = msg.Query("strOutput");
                if (strOutput == "-2")
                {
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Trong đơn đặt hàng " + sOrderID + ". Sản phẩm trong kho không đủ số lượng')</script>");
                    Bind_Order();
                    return;
                }
                flagNone = false;
            }
        }
        if (flagNone == true)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Chọn đơn')</script>");
            Bind_Order();
            return;
        }
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Đã duyệt thành công')</script>");
        Bind_Order();
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        bool flagNone = true;
        for (int i = 0; i < grvMaster.Rows.Count; i++)
        {
            CheckBox chkApprove = (CheckBox)grvMaster.Rows[i].FindControl("chkApprove");
            if (chkApprove.Checked == true)
            {
                string sOrderID = grvMaster.DataKeys[i].Value.ToString();
                cls.UpdateData("update OrderPD set Status='C',EndDate='" + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "' where  OrderID='" + sOrderID + "'");
                flagNone = false;
            }
        }
        if (flagNone == true)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Chọn đơn')</script>");
            Bind_Order();
            return;
        }
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Hủy bỏ thành công')</script>");
        Bind_Order();
    }





    protected void Button2_Click(object sender, EventArgs e)
    {
        clsWebShop cls = new clsWebShop();
        PccMsg msg;
        bool flagNone = true;
        string sOrderID = "";
        string sDateTime = System.DateTime.Now.ToString("yyyyMMddhhmmss");
        try
        {

            for (int i = 0; i < grvMaster.Rows.Count; i++)
            {
                CheckBox chkApprove = (CheckBox)grvMaster.Rows[i].FindControl("chkApprove");
                if (chkApprove.Checked == true)
                {
                    sOrderID = grvMaster.DataKeys[i].Value.ToString();
                    msg = new PccMsg();
                    msg.CreateFirstNode("OrderID", sOrderID);
                    msg.CreateFirstNode("flag", "1");
                    msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                    flagNone = false;
                    string xml = cls.Upd_SignPD(msg.GetXmlStr);
                    msg = new PccMsg(xml);
                    string strOutput = msg.Query("strOutput");
                    if (strOutput == "-2")
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Trong đơn đặt hàng " + sOrderID + ". Sản phẩm trong kho không đủ số lượng')</script>");
                        Bind_Order();
                        return;
                    }
                }

            }

            if (flagNone == true)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Chọn đơn')</script>");
                Bind_Order();
                return;
            }
        }
        catch (Exception ex)
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('" + ex.Message.ToString() + "')</script>");
            Bind_Order();
            return;
        }
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Đã xác nhận thành công')</script>");
        Bind_Order();
    }
    protected void grvMaster_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvMaster.PageIndex = e.NewPageIndex;
        iPageIndex = e.NewPageIndex;
        Bind_Order();
    }
}
